package com.yyfax.ph.home.recommendloan.creditinfo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.bumptech.glide.Glide;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.PermissionFragment;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.imageselector.activity.PhotoSelectorActivity;
import com.yyfax.ph.common.imageselector.activity.PhotoViewActivity;
import com.yyfax.ph.common.imageselector.bean.ImageBean;
import com.yyfax.ph.common.imageselector.factory.AlbumStorageDirFactory;
import com.yyfax.ph.common.imageselector.factory.BaseAlbumDirFactory;
import com.yyfax.ph.common.imageselector.factory.FroyoAlbumDirFactory;
import com.yyfax.ph.common.imageselector.utils.FileUtils;
import com.yyfax.ph.common.utils.BitmapOptimizer;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.utils.ToastUtils;
import com.yyfax.ph.home.imageupload.ChooseImageDialog;
import com.yyfax.ph.home.imageupload.ImageSelectArguments;
import com.yyfax.ph.home.imageupload.UploadImagePresenter;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 无征信报告
 * 身份证反面照片呗替换为身份证复印件照片 20171121
 * Created by ying_he on 2017/11/3.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class NoCreditPaperFragment extends PermissionFragment implements UploadImagePresenter.View, ChoosePictureDialog.ChoosePictureListener, ChooseImageDialog.SelectImageListener {
	private static final String TAG = NoCreditPaperFragment.class.getSimpleName();

	public static final int REQUEST_HOUSE_IMAGE = 0x01;
	public static final int REQUEST_TAKE_PICTURE = 0X02;
	private static final int LOADER_ID_UPLOAD_IMG = 1105;
	private static final String STATE_IMAGE_KIND_TYPE = "state_image_kind_type";
	private static final String IMAGE_BEAN = "image_bean";
	private static final String CURRENT_PHOTO_PATH = "current_photo_path";
	private static final String CHOOSE_FLAG = "choose_flag";
	private static final int CHOOSE_LICENSE_BACKGROUND_FLAG = 0;
	private static final int CHOOSE_CUSTOMER_IMAGE_FLAG = 1;
	private static final int CHOOSE_AUTHORIZE_FLAG = 2;
	private static final int CHOOSE_APPLY_FLAG = 3;

	private static final int HANDLE_COMPRESS_SINGLE = 1;
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	@BindView(R.id.back_pic_iv)
	ImageView mBackPicIv;
	@BindView(R.id.back_pic_reupload_iv)
	ImageView mBackPicReuploadIv;
	@BindView(R.id.back_pic_reupload_ll)
	LinearLayout mBackPicReuploadLl;
	@BindView(R.id.back_pic_ll)
	LinearLayout mBackPicLl;
	@BindView(R.id.handle_pic_iv)
	ImageView mHandlePicIv;
	@BindView(R.id.handle_pic_reupload_iv)
	ImageView mHandlePicReuploadIv;
	@BindView(R.id.handle_pic_reupload_ll)
	LinearLayout mHandlePicReuploadLl;
	@BindView(R.id.handle_pic_ll)
	LinearLayout mHandlePicLl;
	@BindView(R.id.credit_query_auth_pic_iv)
	ImageView mCreditQueryAuthPicIv;
	@BindView(R.id.credit_query_auth_pic_reupload_iv)
	ImageView mCreditQueryAuthPicReuploadIv;
	@BindView(R.id.credit_query_auth_pic_reupload_ll)
	LinearLayout mCreditQueryAuthPicReuploadLl;
	@BindView(R.id.credit_query_auth_pic_ll)
	LinearLayout mCreditQueryAuthPicLl;
	@BindView(R.id.credit_consult_auth_pic_iv)
	ImageView mCreditConsultAuthPicIv;
	@BindView(R.id.credit_consult_pic_reupload_iv)
	ImageView mCreditConsultPicReuploadIv;
	@BindView(R.id.credit_consult_pic_reupload_ll)
	LinearLayout mCreditConsultPicReuploadLl;
	@BindView(R.id.credit_consult_auth_pic_ll)
	LinearLayout mCreditConsultAuthPicLl;
	@BindView(R.id.next_step_tv)
	Button mNextStepTv;

	Unbinder mUnBinder;
	boolean mUploadFlag = false;
	private UploadImagePresenter mUploadPresenter;
	//图片类型
	private int mImageType = CHOOSE_LICENSE_BACKGROUND_FLAG;
	private String[] mImageTypes = {Constants.IMAGE_TYPE_ID_CARD_BACK
			, Constants.IMAGE_TYPE_PORTRAIT, Constants.IMAGE_TYPE_QUERY_AUTHORIZE, Constants.IMAGE_TYPE_QUERY_APPLY};
	//上传提示图
	private int[] mHintImages = {R.drawable.ic_example_back_id_card, R.drawable.ic_example_handle_id_card, R.drawable.ic_example_query_credit_paper, R.drawable.ic_example_consult_credit_paper};
	private List<ImageBean> mImageBeans = new ArrayList<>();
	private int[] mImgEmptyHints = {R.string.upload_id_card_back, R.string.upload_user_check_img, R.string.upload_authorization_paper, R.string.upload_application_paper};
	private boolean mChooseFlag = false;//true表示选择图片上传 false表示拍照上传
	private String mCurrentPhotoPath;//保存拍照的图片路径
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	private Handler mHandler = new ImageHandler(this);
	private UploadCreditPaperFragment.ExtraParamsToUploadCredit mExtraParamsToUploadCredit;
	private int mPermissionRequestCodeExternalStorage = DEFAULT_PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE;
	private int mPermissionRequestCodeCamera = DEFAULT_PERMISSION_REQUEST_CODE_CAMERA_EXTERNAL_STORAGE;

	public static NoCreditPaperFragment newInstance(UploadCreditPaperFragment.ExtraParamsToUploadCredit extraParamsToUploadCredit) {
		NoCreditPaperFragment fragment = new NoCreditPaperFragment();
		Bundle args = new Bundle();
		args.putParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, extraParamsToUploadCredit);
		fragment.setArguments(args);
		return fragment;
	}

	private void readBundle(Bundle bundle) {
		if (bundle != null) {
			mExtraParamsToUploadCredit = bundle.getParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
			mImageType = bundle.getInt(STATE_IMAGE_KIND_TYPE, CHOOSE_LICENSE_BACKGROUND_FLAG);
			if (null != bundle.getParcelableArrayList(IMAGE_BEAN)) {
				mImageBeans = bundle.getParcelableArrayList(IMAGE_BEAN);
			}
			//保存的当前拍照的图片路径
			mCurrentPhotoPath = bundle.getString(CURRENT_PHOTO_PATH);
			mChooseFlag = bundle.getBoolean(CHOOSE_FLAG, false);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_UPLOAD_IMG, null, this);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID_UPLOAD_IMG);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initImageBeanList();

	}

	@Override
	public void onResume() {
		super.onResume();
		if (mUploadFlag && null != mUploadPresenter) {
			showLoading(false);
			mUploadPresenter.uploadImage(getImagePath(), mImageTypes[mImageType]);
			mUploadFlag = false;
		}
	}

	private String getImagePath() {
		if (getSelectedImageList().size() > 0) {
			return getSelectedImageList().get(0).newPath;
		}
		return null;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_no_credit_paper, null);
		mUnBinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}
		boolean restore = false;
		if (null != savedInstanceState) {
			restore = true;
			readBundle(savedInstanceState);
		} else {
			mExtraParamsToUploadCredit = getArguments().getParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
		}
		initView(restore);
	}

	private void initView(boolean restore) {
		// 如果是无征信推荐, 则显示下一步按钮, 否则隐藏, 因为父布局也有一个按钮展示.
		if (mExtraParamsToUploadCredit.bizType == UploadCreditPaperFragment.BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD) {
			mNextStepTv.setVisibility(View.VISIBLE);
		} else {
			mNextStepTv.setVisibility(View.GONE);
		}
		if (restore) {
			if (null != mImageBeans && mImageBeans.size() == 4) {
				//保存的客户审核照
				if (null != mImageBeans.get(CHOOSE_CUSTOMER_IMAGE_FLAG)) {
					resetViewAfterUpload(CHOOSE_CUSTOMER_IMAGE_FLAG, mImageBeans.get(CHOOSE_CUSTOMER_IMAGE_FLAG).newPath, mImageBeans.get(CHOOSE_CUSTOMER_IMAGE_FLAG).isUploaded());
				}
				//保存的身份证反面
				if (null != mImageBeans.get(CHOOSE_LICENSE_BACKGROUND_FLAG)) {
					resetViewAfterUpload(CHOOSE_LICENSE_BACKGROUND_FLAG, mImageBeans.get(CHOOSE_LICENSE_BACKGROUND_FLAG).newPath, mImageBeans.get(CHOOSE_LICENSE_BACKGROUND_FLAG).isUploaded());
				}
				//保存授权书
				if (null != mImageBeans.get(CHOOSE_AUTHORIZE_FLAG)) {
					resetViewAfterUpload(CHOOSE_AUTHORIZE_FLAG, mImageBeans.get(CHOOSE_AUTHORIZE_FLAG).newPath, mImageBeans.get(CHOOSE_AUTHORIZE_FLAG).isUploaded());
				}
				//保存的申请书
				if (null != mImageBeans.get(CHOOSE_APPLY_FLAG)) {
					resetViewAfterUpload(CHOOSE_APPLY_FLAG, mImageBeans.get(CHOOSE_APPLY_FLAG).newPath, mImageBeans.get(CHOOSE_APPLY_FLAG).isUploaded());
				}
			}
		}
	}

	/**
	 * 如果切换回来时身份证图片有更改, 则重新刷新身份证图片.
	 *
	 * @param extraParamsToUploadCredit
	 */
	public void refreshIdCard(UploadCreditPaperFragment.ExtraParamsToUploadCredit extraParamsToUploadCredit) {
		if (extraParamsToUploadCredit != null) {
			mExtraParamsToUploadCredit = extraParamsToUploadCredit;
		}
	}

	private void resetViewAfterUpload(int imageType, String imagePath, boolean succeed) {
		switch (imageType) {
			case CHOOSE_LICENSE_BACKGROUND_FLAG:
				if (succeed) {
					uploadSuccess(imagePath, mBackPicReuploadIv, mBackPicReuploadLl, mBackPicIv);
				} else {
					uploadFailure(imagePath, mBackPicReuploadIv, mBackPicReuploadLl, mBackPicIv);
				}
				break;
			case CHOOSE_CUSTOMER_IMAGE_FLAG:
				if (succeed) {
					uploadSuccess(imagePath, mHandlePicReuploadIv, mHandlePicReuploadLl, mHandlePicIv);
				} else {
					uploadFailure(imagePath, mHandlePicReuploadIv, mHandlePicReuploadLl, mHandlePicIv);
				}
				break;
			case CHOOSE_AUTHORIZE_FLAG:
				if (succeed) {
					uploadSuccess(imagePath, mCreditQueryAuthPicReuploadIv, mCreditQueryAuthPicReuploadLl, mCreditQueryAuthPicIv);
				} else {
					uploadFailure(imagePath, mCreditQueryAuthPicReuploadIv, mCreditQueryAuthPicReuploadLl, mCreditQueryAuthPicIv);
				}
				break;
			case CHOOSE_APPLY_FLAG:
				if (succeed) {
					uploadSuccess(imagePath, mCreditConsultPicReuploadIv, mCreditConsultPicReuploadLl, mCreditConsultAuthPicIv);
				} else {
					uploadFailure(imagePath, mCreditConsultPicReuploadIv, mCreditConsultPicReuploadLl, mCreditConsultAuthPicIv);
				}
				break;
		}
	}

	private void uploadSuccess(String imgPath, ImageView reUploadIv, LinearLayout reUploadLl, ImageView imageView) {
		reUploadIv.setVisibility(View.VISIBLE);
		reUploadLl.setVisibility(View.GONE);
		Glide.with(this).load(imgPath).centerCrop().into(imageView);
	}

	private void uploadFailure(String imgPath, ImageView reUploadIv, LinearLayout reUploadLl, ImageView imageView) {
		reUploadIv.setVisibility(View.GONE);
		reUploadLl.setVisibility(View.VISIBLE);
		Glide.with(this).load(imgPath).centerCrop().into(imageView);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_UPLOAD_IMG:
				return new PresenterLoader<>(getActivity(), new UploadImagePresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_UPLOAD_IMG:
				mUploadPresenter = (UploadImagePresenter) data;
				mUploadPresenter.attach(this);
				break;

			default:
				break;
		}
	}

	private void initImageBeanList() {
		if (null == mImageBeans)
			mImageBeans = new ArrayList<>(4);
		mImageBeans.add(null);
		mImageBeans.add(null);
		mImageBeans.add(null);
		mImageBeans.add(null);
	}

	@OnClick({R.id.back_pic_iv, R.id.back_pic_reupload_iv, R.id.back_pic_reupload_ll
			, R.id.handle_pic_iv, R.id.handle_pic_reupload_iv, R.id.handle_pic_reupload_ll
			, R.id.credit_query_auth_pic_iv, R.id.credit_query_auth_pic_reupload_iv, R.id.credit_query_auth_pic_reupload_ll
			, R.id.credit_consult_auth_pic_iv, R.id.credit_consult_pic_reupload_iv, R.id.credit_consult_pic_reupload_ll, R.id.next_step_tv})
	public void onClicked(View view) {
		switch (view.getId()) {
			case R.id.back_pic_iv: // 身份证反面
				goToChooseImages(CHOOSE_LICENSE_BACKGROUND_FLAG);
				break;
			case R.id.back_pic_reupload_iv:
				showChooseImageDialog(CHOOSE_LICENSE_BACKGROUND_FLAG, true);
				break;
			case R.id.back_pic_reupload_ll:
				reUploadImage(CHOOSE_LICENSE_BACKGROUND_FLAG);
				break;
			case R.id.handle_pic_iv: // 手持身份证
				goToChooseImages(CHOOSE_CUSTOMER_IMAGE_FLAG);
				break;
			case R.id.handle_pic_reupload_iv:
				showChooseImageDialog(CHOOSE_CUSTOMER_IMAGE_FLAG, true);
				break;
			case R.id.handle_pic_reupload_ll:
				reUploadImage(CHOOSE_CUSTOMER_IMAGE_FLAG);
				break;
			case R.id.credit_query_auth_pic_iv: // 征信查询授权书
				goToChooseImages(CHOOSE_AUTHORIZE_FLAG);
				break;
			case R.id.credit_query_auth_pic_reupload_iv:
				showChooseImageDialog(CHOOSE_AUTHORIZE_FLAG, true);
				break;
			case R.id.credit_query_auth_pic_reupload_ll:
				reUploadImage(CHOOSE_AUTHORIZE_FLAG);
				break;
			case R.id.credit_consult_auth_pic_iv: // 征信查阅授权书
				goToChooseImages(CHOOSE_APPLY_FLAG);
				break;
			case R.id.credit_consult_pic_reupload_iv:
				showChooseImageDialog(CHOOSE_APPLY_FLAG, true);
				break;
			case R.id.credit_consult_pic_reupload_ll:
				reUploadImage(CHOOSE_APPLY_FLAG);
				break;
			case R.id.next_step_tv:
				submitCredit();
				break;
			default:
				break;
		}
	}

	public void goToChooseImages(int flag) {
		mImageType = flag;
		showChoosePictureDialog(mHintImages[flag]);
	}

	private void showChoosePictureDialog(int imgId) {
		new ChoosePictureDialog(getActivity(), imgId, this, false).show();
	}

	private void showChooseImageDialog(int flag, boolean showPreview) {
		mImageType = flag;
		new ChooseImageDialog(getActivity(), this, showPreview).show();
	}

	private void reUploadImage(int imageType) {
		mImageType = imageType;
		showLoading(false);
		mUploadPresenter.uploadImage(getImagePath(), mImageTypes[mImageType]);
	}

	private void compress(final String targetCompressPicUrl) {
		final String mImageCacheDir = FileUtils.DEFAULT_SAVE_IMAGE_PATH_UPLOAD;//Constants.DEFAULT_SAVE_IMAGE_PATH + "Cache/HouseImage/";
		if (TextUtils.isEmpty(targetCompressPicUrl)) {
			return;
		}
		File targetCompressFile = new File(targetCompressPicUrl);
		if (!targetCompressFile.exists()) {
			return;
		}

		GlobalVariableConfig.getExecutorService().execute(new Runnable() {
			@Override
			public void run() {
				Map<String, String> currentCompressPicturePath = new HashMap<>();
				String targetImageAbsolutePath = BitmapOptimizer.autoOptimize(getActivity(), targetCompressPicUrl, mImageCacheDir);
				currentCompressPicturePath.put(targetCompressPicUrl, targetImageAbsolutePath);
				Message message = mHandler.obtainMessage();
				message.what = HANDLE_COMPRESS_SINGLE;
				message.obj = currentCompressPicturePath;
				mHandler.sendMessage(message);
			}
		});
	}

	/**
	 * 点击下一步提交前先做判断.
	 */
	public void submitCredit() {
		int size = mImgEmptyHints.length;
		for (int i = 0; i < size; i++) {
			if (checkUploadId(i)) {
				showToast(mImgEmptyHints[i]);
				return;
			}
		}

		UploadCreditPaperFragment.UploadCreditPaperEvent uploadCreditPaperEvent = new UploadCreditPaperFragment.UploadCreditPaperEvent();
		uploadCreditPaperEvent.bizType = mExtraParamsToUploadCredit.bizType;
		uploadCreditPaperEvent.rcmId = mExtraParamsToUploadCredit.rcmId;
		uploadCreditPaperEvent.imageIds = getImgId();
		if (mExtraParamsToUploadCredit.bizType == UploadCreditPaperFragment.BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD) {
			uploadCreditPaperEvent.flag = "";
		}

		EventAgent.post(uploadCreditPaperEvent);
	}

	public List<String> getImgId() {//获取不包括房产图片的图片id，无征信补件
		List<String> imageIds = new ArrayList<>();
		for (ImageBean imageBean : mImageBeans) {
			imageIds.add(imageBean.imageId);
		}
		return imageIds;
	}

	private boolean checkUploadId(int index) {
		return (null == mImageBeans.get(index) || TextUtils.isEmpty(mImageBeans.get(index).imageId));
	}

	public ImageBean getSelectedImageBean() {
		return mImageBeans.get(mImageType);
	}

	public void setSelectedImageBean(ImageBean imageBean) {
		mImageBeans.set(mImageType, imageBean);
	}

	public ArrayList<ImageBean> getSelectedImageList() {
		ArrayList<ImageBean> imageBeans = new ArrayList<>();
		if (null != mImageBeans.get(mImageType))
			imageBeans.add(mImageBeans.get(mImageType));
		return imageBeans;
	}

	public ArrayList<String> getOriginalPaths() {
		ArrayList<String> selectedPaths = new ArrayList<>();
		if (null != getSelectedImageBean()) {
			selectedPaths.add(getSelectedImageBean().originalPath);
		}
		return selectedPaths;
	}

	public void chooseImage() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			ImageSelectArguments arguments = new ImageSelectArguments();
			arguments.showCamera = false;
			arguments.selectMode = PhotoSelectorActivity.SELECT_MODE_SINGLE;
			arguments.remainCount = 1;
			arguments.maxCount = 1;
			arguments.selectedImages = getOriginalPaths();
			arguments.compressedImages = getSelectedImageList();
			PhotoSelectorActivity.startForResult(getActivity(), arguments, REQUEST_HOUSE_IMAGE);
		} else {
			showToast(R.string.check_sdcard);
		}
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@SuppressLint("NewApi")
	public void takePicture() {
		// Persist access permissions.
		String state = Environment.getExternalStorageState();// 判断是否存在sd卡
		if (Environment.MEDIA_MOUNTED.equals(state)) {// 直接调用系统的照相机
			GlobalVariableConfig.setIgnoreGestureFlag(true);
			GlobalVariableConfig.setThirdPartyPageOpenedFlag(true);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
				File file;
				try {
					file = setUpPhotoFile();
					mCurrentPhotoPath = file.getAbsolutePath();
					if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
					} else {
						intent.addFlags(268435456);//可能不需要
						intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
						Uri contentUri = FileProvider.getUriForFile(this.getActivity(), Constants.FILE_PROVIDER_AUTHORITY, file);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
					}
				} catch (IOException e) {
					mCurrentPhotoPath = null;
					e.printStackTrace();
				}
				getActivity().startActivityForResult(intent, REQUEST_TAKE_PICTURE);
				showOrientationToast();
			}
		} else {
			showToast(R.string.check_sdcard);
		}
	}

	private void showOrientationToast() {
		switch (mImageType) {
			case CHOOSE_CUSTOMER_IMAGE_FLAG:
				ToastUtils.showToast(getActivity(), R.string.take_photo_landscape, Toast.LENGTH_LONG);
				break;
			case CHOOSE_LICENSE_BACKGROUND_FLAG:
				ToastUtils.showToast(getActivity(), R.string.take_photo_portrait, Toast.LENGTH_LONG);
				break;
			case CHOOSE_AUTHORIZE_FLAG:
				ToastUtils.showToast(getActivity(), R.string.take_photo_portrait, Toast.LENGTH_LONG);
				break;
			case CHOOSE_APPLY_FLAG:
				ToastUtils.showToast(getActivity(), R.string.take_photo_portrait, Toast.LENGTH_LONG);
				break;
		}
	}

	private String getAlbumName() {
		return "";// 可以在这里建分类目录
	}

	private File getAlbumDir() {
		File storageDir = null;
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						return null;
					}
				}
			}
		}
		return storageDir;
	}

	private File createImageFile() throws IOException {
		String timeStamp = SimpleDateFormat.getDateTimeInstance().format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		return new File(albumF, imageFileName + JPEG_FILE_SUFFIX);
	}

	private File setUpPhotoFile() throws IOException {
		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();
		return f;
	}

	private void handleCameraPhoto() {
		if (mCurrentPhotoPath != null) {
			galleryAddPic();
		}
	}

	private void galleryAddPic() {
		Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		File f = new File(mCurrentPhotoPath);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		getActivity().sendBroadcast(mediaScanIntent);
	}

	@Override
	public void onTakePicture() {
		if (hasCameraPermission(mPermissionRequestCodeCamera)) {
			mChooseFlag = false;
			// TODO: 2017/3/15 忽略手势
			takePicture();
		}
	}

	@Override
	public void onChoosePictures() {
		hasWriteStoragePermission(mPermissionRequestCodeExternalStorage);
		mChooseFlag = true;
		chooseImage();
	}

	@Override
	public void onSelectImageChoose(int type) {
		switch (type) {
			case 0:
				preView();
				break;
			case 1:
				takeFromPicture();
				break;
			case 2:
				chooseFromPhoto();
				break;
		}
	}

	private void preView() {
		ArrayList<String> paths = new ArrayList<>();
		if (null != mImageBeans.get(mImageType)) {
			paths.add(mImageBeans.get(mImageType).newPath);
		}
		PhotoViewActivity.start(getActivity(), paths, -1, false);
	}

	private void takeFromPicture() {
		onTakePicture();
	}

	private void chooseFromPhoto() {
		onChoosePictures();
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeExternalStorage) {
			onChoosePictures();
		} else if (requestCode == mPermissionRequestCodeCamera) {
			onTakePicture();
		}
	}

	@Override
	public void onUploadImage(String filePath, String fileName, String imageId) {
		dismissLoading();
		if (TextUtils.isEmpty(imageId)) {
			if (mImageBeans.get(mImageType) != null) {
				mImageBeans.get(mImageType).status = ImageBean.STATUS_FAIL;
			}
			setUploadFailure();
		} else {
			if (mImageBeans.get(mImageType) != null) {
				mImageBeans.get(mImageType).imageId = imageId;
				mImageBeans.get(mImageType).status = ImageBean.STATUS_SUCCESS;
			}
			setUploadSuccess();
		}
	}

	@Override
	public void onUploadImageFailure(String filePath, String tips) {
		uploadImageFailed(filePath, tips);
	}

	@Override
	public void onUploadImageCancel(String filePath, String tips) {
		uploadImageFailed(filePath, tips);
	}

	private void uploadImageFailed(String filePath, String tips) {
		showToast(tips);
		if (null != mImageBeans.get(mImageType)) {
			mImageBeans.get(mImageType).status = ImageBean.STATUS_FAIL;
		}

		setUploadFailure();
		clearTakePictures();
	}


	private void clearTakePictures() {
		if (!mChooseFlag) {
			mImageBeans.set(mImageType, null);
		}
	}

	public void setUploadSuccess() {
		if (null == mImageBeans.get(mImageType))
			return;
		String imagePath;
		imagePath = mImageBeans.get(mImageType).newPath;
		resetViewAfterUpload(mImageType, imagePath, true);
	}

	public void setUploadFailure() {
		if (null == mImageBeans.get(mImageType))
			return;
		String imagePath;
		imagePath = mImageBeans.get(mImageType).newPath;
		resetViewAfterUpload(mImageType, imagePath, false);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
				case REQUEST_HOUSE_IMAGE:
					ArrayList<ImageBean> newImageBeans = data.getParcelableArrayListExtra(PhotoSelectorActivity.EXTRA_COMPRESSED_BEANS);
					if (null != newImageBeans && newImageBeans.size() > 0) {
						if (null != getSelectedImageBean()) {
							setSelectedImageBean(null);
						}
						setSelectedImageBean(newImageBeans.get(0));
						mUploadFlag = true;
					}
					break;
				case REQUEST_TAKE_PICTURE:
					showLoading(false);
					handleCameraPhoto();
					compress(mCurrentPhotoPath);
					break;
			}
		}
	}

	private void processImages(Object object) {
		Map<String, String> compressSuccessMap = (Map<String, String>) object;
		if (null != compressSuccessMap && compressSuccessMap.size() > 0) {// 说明有压缩成功的文件
			if (null != getSelectedImageBean()) {
				setSelectedImageBean(null);
			}
			ArrayList<ImageBean> newImageBeans = new ArrayList<>();
			for (Map.Entry<String, String> entry : compressSuccessMap.entrySet()) {// TODO: 2017/3/9 不用Map?
				ImageBean imageBean = new ImageBean(entry.getKey(), entry.getValue());
				setSelectedImageBean(imageBean);
				newImageBeans.add(imageBean);
				break;
			}
			if (null != mUploadPresenter) {
				mUploadPresenter.uploadImage(getImagePath(), mImageTypes[mImageType]);
			}
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(STATE_IMAGE_KIND_TYPE, mImageType);
		outState.putParcelableArrayList(IMAGE_BEAN, (ArrayList<ImageBean>) mImageBeans);
		outState.putString(CURRENT_PHOTO_PATH, mCurrentPhotoPath);
		outState.putParcelable(UploadCreditPaperFragment.BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, mExtraParamsToUploadCredit);
		outState.putBoolean(CHOOSE_FLAG, mChooseFlag);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Glide.get(getActivity()).clearMemory();
		mUnBinder.unbind();
	}

	private static class ImageHandler extends Handler {
		WeakReference<NoCreditPaperFragment> mWeakReferenceActivity;

		ImageHandler(NoCreditPaperFragment activity) {
			mWeakReferenceActivity = new WeakReference<>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case HANDLE_COMPRESS_SINGLE:
					if (null != mWeakReferenceActivity) {
						NoCreditPaperFragment noCreditPaperFragment = mWeakReferenceActivity.get();
						noCreditPaperFragment.processImages(msg.obj);
					}
					break;
				default:
					break;
			}
		}
	}

}
